package guoanmaker.provider.business.scheduled;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import guoanmaker.provider.business.dao.ProvideInvoiceInfoDao;
import guoanmaker.provider.business.dao.ProvideOrderFormDao;
import guoanmaker.provider.business.model.ProvideInvoiceInfo;
import guoanmaker.provider.business.model.ProvideOrderForm;
import guoanmaker.provider.business.repository.ProvideInvoiceInfoRepository;
import guoanmaker.provider.business.repository.ProvideOrderFormRepository;
import guoanmaker.provider.business.service.ProvideOrderFormService;
import guoanmaker.provider.helper.common.abstractobj.ApiController;
import guoanmaker.provider.helper.common.util.SystemHelper;
import guoanmaker.provider.helper.jpa.Criteria;
import guoanmaker.provider.helper.jpa.Restrictions;

@Component
public class OrderScheduled {
	@Resource
	private ProvideOrderFormRepository provideOrderFormRepository;
	
	@Resource
	private ProvideOrderFormService provideOrderFormService;
	
	@Resource
	private ProvideOrderFormDao provideOrderFormDao;
	
	@Resource
	private ProvideInvoiceInfoDao provideInvoiceInfoDao;
	
	@Resource
	private ProvideInvoiceInfoRepository provideInvoiceInfoRepository;
	
	/**
	 * 
	* @Description: 定时任务，每天3点查询退款状态 
	* @param 
	* @author Yvonne_MGL 
	* @date 2017年8月8日 下午7:16:43     
	* @return void    
	* @throws 
	 */
	@Scheduled(cron = "0 0 3 * * ?")
	@Transactional
	public void getRefundsState() {
		Criteria<ProvideOrderForm> criteria = new Criteria<>();
		criteria.add(Restrictions.or(Restrictions.eq("orderStatus", "10",true),Restrictions.eq("orderStatus", "11",true)));
		List<ProvideOrderForm> list = provideOrderFormRepository.findAll(criteria);
		if(list!=null&&list.size()>0){
			for (int i = 0; i < list.size(); i++) {
				ProvideOrderForm orderForm=list.get(i);
				String url=ApiController.PAY_URL+"retrieveRefund.php";
				String param="isJava=1&id="+orderForm.getDefrayNumber();
				String result=SystemHelper.httpGetHelper(url, param);
				if(result!=null&&result.equals("4")){
					if(orderForm.getOrderStatus().equals("10")){
						orderForm.setOrderStatus("8");
					}else if(orderForm.getOrderStatus().equals("11")){
						orderForm.setOrderStatus("12");
					}
					provideOrderFormRepository.save(orderForm);
				}
			}
		}
	}
	
	/**
	 * 
	* @Description: 定时任务，每天4点查询对账状态 
	* @param @throws Exception
	* @author Yvonne_MGL 
	* @date 2017年8月8日 下午7:17:29     
	* @return void    
	* @throws 
	 */
	@Scheduled(cron = "0 0 */2 * * ?")
	@Transactional
	public void getCheckState() throws Exception{
		List<ProvideOrderForm> list = provideOrderFormDao.getNotCheckOrder();
		System.out.println(list.size());
		if(list!=null&&list.size()>0){
			
			for (int i = 0; i < list.size(); i++) {
				ProvideOrderForm orderForm=list.get(i);
				String url=ApiController.PAY_URL+"getOrder.php";
				String param="isJava=1&id="+orderForm.getDefrayNumber();
				String json=SystemHelper.httpGetHelper(url, param);
				JSONObject jsonObj = new JSONObject(json);
				String status=jsonObj.getString("status");
				if(status!=null&&status.equals("SUCCESS")){
					JSONObject data=jsonObj.getJSONObject("data");
					String state=data.getString("status");
					if(state!=null&&(state.equals("3")||state.equals("6"))){
						Double fee=Double.parseDouble(data.getString("fee"));
						Double commission=Double.parseDouble(data.getString("divide_amount"));
						Double bail=Double.parseDouble(data.getString("deposit_amount"));
						orderForm.setFee(new BigDecimal(fee/100));
						orderForm.setCommission(new BigDecimal(commission/100));
						orderForm.setBail(new BigDecimal(bail/100));
						orderForm.setIsCheck("1");
						provideOrderFormRepository.save(orderForm);
					}
				}
				
			}
		}
	}
	
	/**
	 * 
	* @Description: 轮循任务，5分钟执行一次，关闭24小时未支付和未接单的订单 
	* @param 
	* @author Yvonne_MGL 
	* @date 2017年8月8日 下午7:17:56     
	* @return void    
	* @throws 
	 */
	@Scheduled(fixedRate = 300000)
	public void closeOrder()throws Exception{
		
		Date date=SystemHelper.getLess24Hour();
		Criteria<ProvideOrderForm> criteria = new Criteria<>();
		criteria.add(Restrictions.or(Restrictions.eq("orderStatus", "1",true),Restrictions.eq("orderStatus", "14",true)));
		criteria.add(Restrictions.gte("placeOrderTime", date,true));
		List<ProvideOrderForm> list = provideOrderFormRepository.findAll(criteria);
		if(list!=null&&list.size()>0){
			for (int i = 0; i < list.size(); i++) {
				provideOrderFormService.closeOrder(list.get(i).getId(),"1",null); 
			}
		}
		
		Criteria<ProvideOrderForm> c = new Criteria<>();
		c.add(Restrictions.eq("orderStatus", "2",true));
		c.add(Restrictions.gte("defrayTime", date,true));
		List<ProvideOrderForm> l = provideOrderFormRepository.findAll(c);
		if(l!=null&&l.size()>0){
			for (int i = 0; i < l.size(); i++) {
				provideOrderFormService.closeOrder(l.get(i).getId(),"2",null);  
			}
		}
	}
	
	/**
	 * 
	* @Description: 关闭10分钟未支付的秒杀订单 
	* @param @throws Exception
	* @author Yvonne_MGL 
	* @date 2017年11月29日 下午4:25:16     
	* @return void    
	* @throws 
	 */
	@Scheduled(fixedRate = 5000)
	public void close12Order()throws Exception{
		List<ProvideOrderForm> list12 = provideOrderFormDao.getOrder12();
		if(list12!=null&&list12.size()>0){
			for (int i = 0; i < list12.size(); i++) {
				provideOrderFormService.closeOrder(list12.get(i).getId(),"1",null); 
			}
		}
	}
	
	/**
	 * 
	* @Description: 轮循任务，6小时执行一次，查询服务商开发票状态 
	* @param 
	* @author Yvonne_MGL 
	* @date 2017年11月17日    
	* @return void    
	* @throws 
	 */
	@Scheduled(cron = "0 0 */6 * * ?")
	@Transactional
	public void getInvoiceState() throws Exception{
		List<ProvideInvoiceInfo> list=provideInvoiceInfoDao.getProvideInvoiceInfos();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		if(list!=null&&list.size()>0){
			for (int i = 0; i < list.size(); i++) {
				ProvideInvoiceInfo info=list.get(i);
				String url=ApiController.PAY_URL+"selInvoice.php";
				String param="isJava=1&invoiceId="+info.getId();
				String json=SystemHelper.httpGetHelper(url, param);
				JSONObject jsonObj = new JSONObject(json);
				String status=jsonObj.getString("status");
				if(status!=null&&status.equals("SUCCESS")){
					String invoiceState=jsonObj.getString("statusInvoice");
					String billingTime=jsonObj.getString("signTime");
					if(invoiceState!=null&&invoiceState.equals("1")){
						info.setInvoiceState("1");
						info.setBillingTime(sdf.parse(billingTime));
						provideInvoiceInfoRepository.save(info);
					}
				}
			}
		}
	}
	
	//@Scheduled(cron = "0 0 0 1 1 ?")
	@Scheduled(cron = "0 0 */6 * * ?")
	@Transactional
	public void getDrivingInvoice() throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String url=ApiController.PAY_URL+"allInvoice.php";
		String param="isJava=1";
		String json=SystemHelper.httpGetHelper(url, param);
		System.err.println("123:"+json);
		JSONObject jsonObj = new JSONObject(json);
		String status=jsonObj.getString("status");
		if(status!=null&&status.equals("SUCCESS")){
			JSONArray jsonArray = jsonObj.getJSONArray("message");
			if(jsonArray.length()>0){
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					String result=provideInvoiceInfoDao.getInvoiceCaiwuid(jsonObject.getString("invoiceId"));
					if(result.equals("1")){
						ProvideInvoiceInfo info=new ProvideInvoiceInfo();
						info.setCaiwuid(jsonObject.getString("invoiceId"));
						info.setBusinessid(jsonObject.getString("originalId"));
						info.setInvoiceType(jsonObject.getString("type"));
						info.setAmountOfMoney(new BigDecimal(Double.parseDouble(jsonObject.getString("amount"))/100));
						info.setMailingAddress(jsonObject.getString("address"));
						info.setInvoiceState(jsonObject.getString("status"));
						String createTime=jsonObject.getString("createTime");
						if(createTime!=null&&!createTime.equals("")){
							info.setApplyTime(sdf.parse(createTime));
						}
						String billingTime=jsonObject.getString("signTime");
						if(billingTime!=null&&!billingTime.equals("")){
							info.setBillingTime(sdf.parse(billingTime));
						}
						info.setChannel(jsonObject.getString("types"));
						String invoiceid=provideInvoiceInfoDao.getInvoiceId(jsonObject.getString("originalId"));
						info.setInvoiceid(invoiceid);
						provideInvoiceInfoRepository.save(info);
					}
				}
			}
		}
	}

}
